package com.geoai.featgeoaivideo

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.geoai.basiclib.base.fragment.BaseVVDFragment
import com.geoai.basiclib.ext.gone
import com.geoai.basiclib.ext.visible
import com.geoai.featgeoaivideo.databinding.FragmentGeoaiVideoBinding
import com.geoai.featgeoaivideo.mvi.eis.GeoaiVideoEffect
import com.geoai.featgeoaivideo.mvi.eis.GeoaiVideoIntent
import com.geoai.featgeoaivideo.mvi.eis.GeoaiVideoState
import com.geoai.featgeoaivideo.mvi.vm.GeoaiVideoViewModel
import com.geoai.modservice.di.ARouterPath
import com.geoai.modservice.di.eventbus.CameraLinesStyle
import com.geoai.modservice.di.eventbus.DisplayCameraLinesStyle
import com.geoai.modservice.di.eventbus.ToggleFpvSize
import com.geoai.modservice.di.eventbus.ToggleSize
import com.geoai.uicore.custom.ui.GEOUIMessageDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs

/**
 * @Author      : Ronny
 * @Email       : Ronny_xie@hotmail.com
 * @Date        : on 2024-04-10 15:21.
 * @Description :
 */
@Route(path = ARouterPath.PATH_UI_CAMERA_VIDEO)
class GeoaiVideoFragment: BaseVVDFragment<GeoaiVideoViewModel, FragmentGeoaiVideoBinding>() {

    override fun hasRegisterEventBus(): Boolean = true

    override fun startObserve() {
        super.startObserve()

        lifecycleScope.launch(Dispatchers.Main) {
            mViewModel.uiEffectFlow.collect { effect->
                when (effect) {
                    is GeoaiVideoEffect.StartPlay -> {
                        mBinding.videoFeederView.releasePlayer()
                        mBinding.videoFeederView.initPlayer(effect.source) { it.startPlayer() }
                    }
                    is GeoaiVideoEffect.UpdateFpvSource -> { mBinding.tvFpvSource.text = effect.source }
                    is GeoaiVideoEffect.UpdateCameraLineStyle -> {
                        updateCameraLineStyle(effect.style) }
                }
            }
        }

        lifecycleScope.launch(Dispatchers.Main) {
            mViewModel.uiStateFlow.collect { state ->
                when (state) {
                    GeoaiVideoState.BigFpv -> {
                        mBinding.tvFpvSource.gone()
                        mBinding.imgSwitcher.gone()
                    }
                    GeoaiVideoState.MiniFpv -> {
                        mBinding.tvFpvSource.visible()
                        mBinding.imgSwitcher.visible()
                    }
                }
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun init(savedInstanceState: Bundle?) {

        mBinding.imgSwitcher.setOnClickListener { showSwitchFpvSourceDialog() }

        mBinding.videoFeederView.setOnTouchListener { _, motionEvent ->
            fun isTouchSlop(motionEvent: MotionEvent): Boolean {
                return abs(motionEvent.x - mViewModel.fpvTouchPosition.first) < 20 && abs(motionEvent.y - mViewModel.fpvTouchPosition.second) < 20
            }
            when (motionEvent.action) {
                MotionEvent.ACTION_DOWN -> mViewModel.fpvTouchPosition = Pair(motionEvent.x.toInt(), motionEvent.y.toInt())
                MotionEvent.ACTION_UP -> {
                    if (isTouchSlop(motionEvent)) {
                        mViewModel.sendUiIntent(GeoaiVideoIntent.OnFpvTouchEvent)
                    }
                }
            }
            true
        }
    }

    private fun showSwitchFpvSourceDialog() {
        GEOUIMessageDialog()
            .setTitle(getString(R.string.txt_comfirm_switch_camera_source))
            .setSecondaryButton(getString(R.string.cancel)) {  }
            .setPrimaryButton(getString(R.string.confirm)) { mViewModel.sendUiIntent(GeoaiVideoIntent.ToggleFpvSource) }
            .show(parentFragmentManager)
    }

    private fun updateCameraLineStyle(style: CameraLinesStyle) {
        val bg = when (style) {
            CameraLinesStyle.NONE -> null
            CameraLinesStyle.A -> R.drawable.bg_camera_line_style_a
            CameraLinesStyle.B -> R.drawable.bg_camera_line_style_b
            CameraLinesStyle.C -> R.drawable.bg_camera_line_style_c
        }
        mBinding.imgCameraLinesStyle.background = bg?.let { resources.getDrawable(it) }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBus(event: ToggleFpvSize) {
        when (event.type) {
            ToggleSize.BIG -> mViewModel.sendUiState(GeoaiVideoState.BigFpv)
            ToggleSize.MINI, ToggleSize.ICON -> mViewModel.sendUiState(GeoaiVideoState.MiniFpv)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBus(event: DisplayCameraLinesStyle) {
        updateCameraLineStyle(event.style)
        mViewModel.sendUiIntent(GeoaiVideoIntent.SaveCameraLineStyle(CameraLinesStyle.valueOf(event.style.name)))
    }
}